@{
    ViewData["Title"] = "报工信息";
}

@section Styles {
    <style>
        /* 页面整体样式优化 */
        .layui-fluid {
            padding: 20px;
            background-color: #f5f5f5;
            min-height: 100vh;
        }

        /* 卡片样式优化 */
        .layui-card {
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            border: none;
            margin-bottom: 20px;
            background: white;
            overflow: hidden;
        }

        .layui-card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-bottom: none;
        }

        .layui-card-header h3 {
            margin: 0;
            font-size: 20px;
            font-weight: 600;
            color: white;
        }

        .layui-card-body {
            background-color: white;
            padding: 25px;
        }

        /* 搜索区域样式 */
        .search-area {
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
            border: 1px solid #e9ecef;
        }

        .search-form {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: flex-end;
        }

        .search-form .layui-form-item {
            margin-bottom: 0;
            flex: 1;
            min-width: 200px;
        }

        .search-buttons {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
        }

        /* 按钮样式优化 */
        .layui-btn {
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
            padding: 8px 20px;
            border: none;
            position: relative;
            overflow: hidden;
        }

        .layui-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
        }

        .layui-btn:hover::before {
            left: 100%;
        }

        .layui-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }

        .layui-btn-normal {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .layui-btn-normal:hover {
            background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
        }

        .layui-btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
        }

        .layui-btn-danger:hover {
            background: linear-gradient(135deg, #ff5252 0%, #d32f2f 100%);
        }

        .layui-btn-primary {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            color: #495057;
            border: 2px solid #dee2e6;
        }

        .layui-btn-primary:hover {
            background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
            border-color: #adb5bd;
        }

        /* 输入框样式优化 */
        .layui-input, .layui-select {
            border-radius: 8px;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
            padding: 10px 15px;
            background: white;
        }

        .layui-input:focus, .layui-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            transform: translateY(-1px);
        }

        /* 表格容器样式 */
        .table-container {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            border: 1px solid #e9ecef;
            position: relative;
        }
        
        /* 可拖拽表格容器 */
        .draggable-table-wrapper {
            width: 100%;
            overflow-x: auto;
            overflow-y: hidden;
            position: relative;
            max-height: calc(100vh - 280px);
        }

        /* 表格样式优化 */
        .layui-table {
            border-radius: 0;
            border: none;
            background: white;
            font-size: 13px;
        }

        .layui-table thead tr {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .layui-table thead tr th {
            background: transparent;
            color: white;
            font-weight: 600;
            border-bottom: none;
            position: relative;
            user-select: none;
            min-width: 80px;
            padding: 16px 12px;
            text-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }

        .layui-table tbody tr {
            transition: all 0.3s ease;
            border-left: 4px solid transparent;
        }

        .layui-table tbody tr:nth-child(even) {
            background-color: #fafbff;
        }

        .layui-table tbody tr:hover {
            background: linear-gradient(135deg, #f0f3ff 0%, #ffffff 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(102, 126, 234, 0.15);
            border-left-color: #667eea;
        }

        .layui-table tbody tr.selected {
            background: linear-gradient(135deg, #e8f4ff 0%, #f0f8ff 100%);
            border-left-color: #1890ff;
        }

        .layui-table tbody tr td {
            padding: 14px 12px;
            border-bottom: 1px solid #f0f2f5;
            vertical-align: middle;
        }
        
        /* 列宽拖拽样式 */
        .layui-table th .resize-handle {
            position: absolute;
            right: -2px;
            top: 0;
            bottom: 0;
            width: 4px;
            cursor: col-resize;
            background: transparent;
            z-index: 10;
        }
        
        .layui-table th .resize-handle:hover {
            background: #1890ff;
        }
        
        .layui-table th.resizing {
            border-right: 2px solid #1890ff;
        }
        
        /* 固定列样式 */
        .layui-table th.fixed-column {
            position: sticky;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            z-index: 20;
            border-right: 2px solid rgba(255,255,255,0.2);
        }
        
        .layui-table td.fixed-column {
            position: sticky;
            background: #fff;
            z-index: 15;
            border-right: 2px solid #e8f4ff;
            box-shadow: 2px 0 4px rgba(0,0,0,0.05);
        }
        
        /* 固定列的复选框列 */
        .layui-table th:first-child.fixed-column {
            width: 50px;
            left: 0px;
        }
        
        .layui-table td:first-child.fixed-column {
            width: 50px;
            left: 0px;
        }
        
        /* 表格滚动条美化 */
        .draggable-table-wrapper::-webkit-scrollbar {
            height: 8px;
        }
        
        .draggable-table-wrapper::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        .draggable-table-wrapper::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        
        .draggable-table-wrapper::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        
        /* 表格宽度控制 */
        .layui-table {
            min-width: 2200px;
            width: auto;
        }
        
        /* 拖拽时的全局样式 */
        body.col-resizing {
            cursor: col-resize !important;
            user-select: none;
        }
        
        body.col-resizing * {
            cursor: col-resize !important;
        }

        /* 表头排序样式 */
        .layui-table th[onclick] {
            position: relative;
            transition: all 0.2s ease;
            cursor: pointer;
            user-select: none;
        }
        
        .layui-table th[onclick]:hover {
            background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
            color: #667eea;
        }
        
        .layui-table th .layui-icon-up-down {
            color: #adb5bd;
            margin-left: 5px;
            font-size: 12px;
            transition: color 0.2s ease;
        }
        
        .layui-table th .layui-icon-up {
            color: #667eea;
            margin-left: 5px;
            font-size: 12px;
        }
        
        .layui-table th .layui-icon-down {
            color: #667eea;
            margin-left: 5px;
            font-size: 12px;
        }

        /* 复选框样式优化 */
        .layui-form-checkbox {
            margin: 0;
        }

        .layui-form-checkbox[lay-skin="primary"] i {
            border-radius: 4px;
            border: 2px solid #dee2e6;
            transition: all 0.2s ease;
        }

        .layui-form-checkbox[lay-skin="primary"]:hover i {
            border-color: #667eea;
        }

        .layui-form-checked[lay-skin="primary"] i {
            background-color: #667eea;
            border-color: #667eea;
        }

        /* 分页样式 */
        .layui-laypage {
            text-align: center;
            padding: 20px 0;
            background: white;
            border-radius: 0 0 12px 12px;
        }

        .layui-laypage a, .layui-laypage span {
            border-radius: 6px;
            margin: 0 3px;
            transition: all 0.2s ease;
        }

        .layui-laypage a:hover {
            background-color: #667eea;
            color: white;
            transform: translateY(-1px);
        }

        /* 工单状态标签样式 */
        .status-tag {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 14px;
            border-radius: 25px;
            font-size: 12px;
            font-weight: 600;
            color: white;
            text-align: center;
            min-width: 70px;
            position: relative;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
            transition: all 0.3s ease;
        }

        .status-tag::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
            transition: left 0.5s;
        }

        .status-tag:hover::before {
            left: 100%;
        }

        .status-tag::after {
            content: '';
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: rgba(255,255,255,0.8);
            animation: pulse 2s infinite;
        }

        @@keyframes pulse {
            0%, 100% { opacity: 0.8; transform: scale(1); }
            50% { opacity: 1; transform: scale(1.2); }
        }

        .status-pending {
            background: linear-gradient(135deg, #ff9500 0%, #ff6b35 100%);
        }

        .status-processing {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .status-completed {
            background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
        }

        .status-cancelled {
            background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
        }

        /* 优先级标签样式 */
        .priority-tag {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 500;
            color: white;
        }

        .priority-high {
            background-color: #ff5722;
        }

        .priority-medium {
            background-color: #ff9800;
        }

        .priority-low {
            background-color: #4caf50;
        }

        /* 排序列样式优化 */
        th[onclick] {
            position: relative;
            transition: all 0.2s ease;
        }
        
        th[onclick]:hover {
            background-color: #f8f9ff !important;
            color: #667eea !important;
        }
        
        th[onclick] .layui-icon {
            margin-left: 4px;
            font-size: 12px;
            transition: color 0.2s ease;
        }
        
        /* 激活状态的排序列 */
        th.active-sort {
            background-color: #f0f3ff !important;
            color: #667eea !important;
            font-weight: 600;
        }
        
        th.active-sort .layui-icon {
            color: #667eea;
        }

        /* 审批状态进度条样式 */
        .approval-status {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            transition: all 0.3s ease;
            cursor: default;
            position: relative;
            overflow: hidden;
        }

        .approval-status::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(45deg, transparent 30%, rgba(255,255,255,0.2) 50%, transparent 70%);
            transform: translateX(-100%);
            transition: transform 0.6s;
        }

        .approval-status:hover::before {
            transform: translateX(100%);
        }
        
        .approval-status.pending {
            background: linear-gradient(135deg, #fff7e6 0%, #ffecc7 100%);
            color: #d48806;
            border: 2px solid #ffec3d;
            box-shadow: 0 2px 8px rgba(255, 193, 7, 0.3);
        }
        
        .approval-status.approved {
            background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
            color: #389e0d;
            border: 2px solid #73d13d;
            box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
        }
        
        .approval-status.rejected {
            background: linear-gradient(135deg, #fff2f0 0%, #ffccc7 100%);
            color: #cf1322;
            border: 2px solid #ff7875;
            box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
        }
        
        .approval-status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            display: inline-block;
            position: relative;
            animation: statusPulse 2s infinite;
        }

        @@keyframes statusPulse {
            0%, 100% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.3); opacity: 0.7; }
        }
        
        .approval-status.pending .approval-status-dot {
            background-color: #fa8c16;
            box-shadow: 0 0 6px rgba(250, 140, 22, 0.6);
        }
        
        .approval-status.approved .approval-status-dot {
            background-color: #52c41a;
            box-shadow: 0 0 6px rgba(82, 196, 26, 0.6);
        }
        
        .approval-status.rejected .approval-status-dot {
            background-color: #ff4d4f;
            box-shadow: 0 0 6px rgba(255, 77, 79, 0.6);
        }

        /* 简化的加载动画 */
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            border-radius: 12px;
        }

        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
        }

        /* 表单子区域标题样式 */
        .form-section-title {
            background-color: #20c997; /* 绿色系，与截图接近 */
            color: #fff;
            font-size: 16px;
            font-weight: 600;
            padding: 6px 12px;
            border-radius: 4px;
            margin: 20px 0 10px;
        }

        /* 数据高亮显示 */
        .data-highlight {
            font-weight: 600;
            color: #1890ff;
        }

        .quantity-display {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 2px 8px;
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border-radius: 12px;
            border: 1px solid #bae7ff;
            font-weight: 500;
            color: #0958d9;
        }

        .time-display {
            font-family: 'Consolas', 'Monaco', monospace;
            color: #722ed1;
            background: linear-gradient(135deg, #f9f0ff 0%, #efdbff 100%);
            padding: 2px 6px;
            border-radius: 8px;
            border: 1px solid #d3adf7;
            font-size: 11px;
        }

        /* 产品编号美化 */
        .product-code {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 10px;
            background: linear-gradient(135deg, #fff7e6 0%, #ffecc7 100%);
            border-radius: 16px;
            border: 1px solid #ffd666;
            color: #d48806;
            font-weight: 500;
            font-size: 12px;
        }

        .product-code::before {
            content: '📦';
            font-size: 10px;
        }

        /* 工序名称美化 */
        .process-name {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 10px;
            background: linear-gradient(135deg, #f0f5ff 0%, #d6e4ff 100%);
            border-radius: 16px;
            border: 1px solid #91caff;
            color: #1677ff;
            font-weight: 500;
            font-size: 12px;
        }

        .process-name::before {
            content: '⚙️';
            font-size: 10px;
        }

        /* 数字数据美化 */
        .numeric-data {
            font-family: 'Consolas', 'Monaco', monospace;
            font-weight: 600;
            text-align: right;
        }

        .numeric-data.positive {
            color: #52c41a;
        }

        .numeric-data.zero {
            color: #8c8c8c;
        }

        .numeric-data.negative {
            color: #ff4d4f;
        }

        /* 表格行选中状态 */
        .layui-table tbody tr td input[type="checkbox"]:checked + * {
            background-color: #e6f7ff;
        }

        /* 表格数据为空时的样式 */
        .empty-data {
            color: #bfbfbf;
            font-style: italic;
            text-align: center;
        }

        /* 表格加载状态 */
        .table-loading {
            position: relative;
        }

        .table-loading::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            z-index: 999;
        }

        /* 表格行动画效果 */
        @@keyframes rowSlideIn {
            from {
                opacity: 0;
                transform: translateX(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .layui-table tbody tr {
            animation: rowSlideIn 0.3s ease-out;
        }

        .layui-table tbody tr:nth-child(1) { animation-delay: 0.1s; }
        .layui-table tbody tr:nth-child(2) { animation-delay: 0.15s; }
        .layui-table tbody tr:nth-child(3) { animation-delay: 0.2s; }
        .layui-table tbody tr:nth-child(4) { animation-delay: 0.25s; }
        .layui-table tbody tr:nth-child(5) { animation-delay: 0.3s; }

        /* 表头图标动画 */
        .layui-table th[onclick] .layui-icon {
            transition: transform 0.2s ease;
        }

        .layui-table th[onclick]:hover .layui-icon {
            transform: scale(1.2);
        }

        /* 复选框动画 */
        .layui-form-checkbox[lay-skin="primary"] i {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .layui-form-checkbox[lay-skin="primary"]:hover i {
            transform: scale(1.1);
        }

        .layui-form-checked[lay-skin="primary"] i {
            animation: checkboxPop 0.3s ease;
        }

        @@keyframes checkboxPop {
            0% { transform: scale(1); }
            50% { transform: scale(1.2); }
            100% { transform: scale(1); }
        }
    </style>
}

<div class="layui-fluid">
    <!-- 工单管理卡片 -->
    <div class="layui-card">
        <div class="layui-card-header">
            <h3><i class="layui-icon layui-icon-form" style="margin-right: 8px;"></i>报工信息管理</h3>
        </div>
        <div class="layui-card-body">
            <!-- 搜索区域 -->
            <div class="search-area">
                <form class="layui-form search-form" lay-filter="searchForm">
                    <div class="layui-form-item">
                        <label class="layui-form-label">工序名称</label>
                        <div class="layui-input-block">
                            <select id="processSelect" lay-filter="processSelect" class="layui-select">
                                <option value="">请选择工序名称</option>
                            </select>
                        </div>
                    </div>
                    <div class="search-buttons">
                        <button type="button" class="layui-btn layui-btn-normal" onclick="searchData()">
                            <i class="layui-icon layui-icon-search"></i> 查询
                        </button>
                        <button type="button" class="layui-btn layui-btn-primary" onclick="resetSearch()">
                            <i class="layui-icon layui-icon-refresh"></i> 重置
                        </button>
                        <button type="button" class="layui-btn layui-btn-primary" onclick="showAdvancedSearch()">
                            <i class="layui-icon layui-icon-more-vertical"></i> 高级查询
                        </button>
                        <button type="button" class="layui-btn layui-btn-primary" onclick="showColumnSettings()">
                            <i class="layui-icon layui-icon-set-fill"></i> 列设置
                        </button>
                    </div>
                </form>
            </div>

            <!-- 操作按钮区域 -->
            <div class="search-buttons" style="margin-bottom: 20px;">
                <button type="button" class="layui-btn layui-btn-normal" onclick="showAddWorkReport()">
                    <i class="layui-icon layui-icon-add-1"></i> 新增报工
                </button>
                <button type="button" class="layui-btn layui-btn-primary" id="editBtn" disabled onclick="editSelected()">
                    <i class="layui-icon layui-icon-edit"></i> 编辑
                </button>
                <button type="button" class="layui-btn layui-btn-danger" id="deleteBtn" disabled onclick="deleteSelected()">
                    <i class="layui-icon layui-icon-delete"></i> 批量删除
                </button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="exportWorkReport()">
                    <i class="layui-icon layui-icon-export"></i> 导出数据
                </button>
                
                <!-- 拖拽功能提示 -->
                <div style="float: right; margin-left: 20px;">
                    <span style="font-size: 12px; color: #666; background: #f0f9ff; padding: 6px 12px; border-radius: 4px; border: 1px solid #bae6fd;">
                        <i class="layui-icon layui-icon-tips" style="color: #0284c7; margin-right: 4px;"></i>
                        💡 可拖拽表头边缘调整列宽 | 前3列固定显示 | 支持水平滚动
                    </span>
                </div>
            </div>

            <!-- 操作提示 -->
            <div id="selectionHint" style="display:block;background:#fff7e6;border:1px solid #ffd591;color:#ad6800;padding:12px 16px;border-radius:8px;margin-bottom:20px;font-size:13px;">
                <i class="layui-icon layui-icon-tips" style="margin-right:6px;color:#ff9c6e;"></i>请先选择要编辑或删除的行
            </div>

            <!-- 调试提示信息 -->
            <div id="debugHint" style="display:block;background:#e6f4ff;border:1px solid #91caff;color:#1677ff;padding:12px 16px;border-radius:8px;margin-bottom:20px;font-size:13px;">
                <i class="layui-icon layui-icon-survey" style="margin-right:6px;"></i>
                <strong>📋 调试信息:</strong> 
                已添加产品数据调试日志，如发现产品规格为空请：
                <br>1️⃣ 打开浏览器开发者工具(F12) → Console面板
                <br>2️⃣ 新增报工时查看日志输出，确认产品数据是否正确加载
                <br>3️⃣ 如产品数据中spec字段为空，请检查数据库产品表数据
                <button type="button" onclick="$('#debugHint').hide()" style="float:right;background:none;border:none;color:#1677ff;cursor:pointer;">✕</button>
            </div>

            <!-- 表格容器 -->
            <div class="table-container">
                <div class="draggable-table-wrapper">
                    <table class="layui-table" id="workReportTable" lay-filter="workReportTable">
                        <thead>
                            <tr id="workReportHeaderRow">
                                <th style="width: 50px;">
                                    <input type="checkbox" lay-filter="checkAll" lay-skin="primary" id="checkAll">
                                </th>
                            </tr>
                        </thead>
                        <tbody id="workReportTableBody">
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>

                <!-- 分页 -->
                <div id="workReportPager"></div>
            </div>
        </div>
    </div>
</div>

<!-- 模态框区域 -->
<!-- 高级查询模态框 -->
<div id="advancedSearchModal" style="display:none; padding:20px 30px 10px 10px;">
    <form class="layui-form" id="advancedSearchForm" lay-filter="advForm">
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">工序名称</label>
                    <div class="layui-input-block">
                        <select id="advProcessName" lay-filter="advProcessName" class="layui-select">
                            <option value="">请选择工序名称</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">产品编号</label>
                    <div class="layui-input-block">
                        <input type="text" id="advProductCode" placeholder="产品编号" class="layui-input" />
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">产品名称</label>
                    <div class="layui-input-block">
                        <input type="text" id="advProductName" placeholder="产品名称" class="layui-input" />
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md8">
                <div class="layui-form-item">
                    <label class="layui-form-label">工序状态</label>
                    <div class="layui-input-block">
                        <input type="radio" name="advProcessStatus" value="" title="全部" checked />
                        <input type="radio" name="advProcessStatus" value="0" title="未开始" />
                        <input type="radio" name="advProcessStatus" value="1" title="进行中" />
                        <input type="radio" name="advProcessStatus" value="2" title="已完成" />
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">生产人员</label>
                    <div class="layui-input-block">
                        <select id="advProducer" class="layui-select">
                            <option value="">请选择生产人员</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">工单</label>
                    <div class="layui-input-block">
                        <select id="advWorkOrder" class="layui-select">
                            <option value="">请选择工单</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">单位</label>
                    <div class="layui-input-block">
                        <select id="advUnit" class="layui-select">
                            <option value="">请选择单位</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">报工数</label>
                    <div class="layui-input-inline" style="width:100px;">
                        <input type="number" id="advReportQtyFrom" placeholder="起" class="layui-input" />
                    </div>
                    <div class="layui-form-mid">至</div>
                    <div class="layui-input-inline" style="width:100px;">
                        <input type="number" id="advReportQtyTo" placeholder="止" class="layui-input" />
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">良品数</label>
                    <div class="layui-input-inline" style="width:100px;">
                        <input type="number" id="advGoodQtyFrom" placeholder="起" class="layui-input" />
                    </div>
                    <div class="layui-form-mid">至</div>
                    <div class="layui-input-inline" style="width:100px;">
                        <input type="number" id="advGoodQtyTo" placeholder="止" class="layui-input" />
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">开始时间</label>
                    <div class="layui-input-inline" style="width:160px;">
                        <input type="text" id="advStartTimeFrom" placeholder="开始时间" class="layui-input" />
                    </div>
                    <div class="layui-form-mid">至</div>
                    <div class="layui-input-inline" style="width:160px;">
                        <input type="text" id="advStartTimeTo" placeholder="结束时间" class="layui-input" />
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">结束时间</label>
                    <div class="layui-input-inline" style="width:160px;">
                        <input type="text" id="advEndTimeFrom" placeholder="开始时间" class="layui-input" />
                    </div>
                    <div class="layui-form-mid">至</div>
                    <div class="layui-input-inline" style="width:160px;">
                        <input type="text" id="advEndTimeTo" placeholder="结束时间" class="layui-input" />
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<!-- 列设置模态框 -->
<div id="columnSettingsModal" style="display:none; padding:20px 30px 10px 10px;">
    <p style="background:#f2fdfb;padding:10px 15px;color:#009688;">拖动列名可调整表格列显示顺序</p>
    <table class="layui-table" style="margin:0;">
        <thead>
            <tr>
                <th style="width:40px;">#</th>
                <th>列名</th>
                <th style="width:100px;">是否显示</th>
            </tr>
        </thead>
        <tbody id="columnSettingsTBody"></tbody>
    </table>
</div>

<!-- 新增报工模态框 -->
<div id="addWorkReportModal" style="display:none; padding:20px 30px 10px 10px;">
    <form class="layui-form" id="addWorkReportForm" lay-filter="addForm">
        <input type="hidden" id="workReportId" />
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label"><span style="color:red;">*</span>工单号</label>
                    <div class="layui-input-block">
                        <select id="addWorkOrderCode" required lay-verify="required" class="layui-select">
                            <option value="">请选择工单</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label"><span style="color:red;">*</span>工序名称</label>
                    <div class="layui-input-block">
                        <select id="addProcessName" class="layui-select">
                            <option value="">请选择工序名称</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label"><span style="color:red;">*</span>产品编号</label>
                    <div class="layui-input-block">
                        <select id="addProductCode" class="layui-select">
                            <option value="">请选择产品编号</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label"><span style="color:red;">*</span>产品名称</label>
                    <div class="layui-input-block">
                        <select id="addProductName" class="layui-select">
                            <option value="">请选择产品名称</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label"><span style="color:red;">*</span>报工数</label>
                    <div class="layui-input-block">
                        <input type="number" id="addReportQty" required lay-verify="number" placeholder="报工数" class="layui-input" />
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">良品数</label>
                    <div class="layui-input-block">
                        <input type="number" id="addGoodQty" placeholder="良品数" class="layui-input" />
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">不良品数</label>
                    <div class="layui-input-block">
                        <input type="number" id="addDefectiveQty" placeholder="不良品数" class="layui-input" />
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label"><span style="color:red;">*</span>开始时间</label>
                    <div class="layui-input-block">
                        <input type="text" id="addStartTime" placeholder="开始时间" class="layui-input" />
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label"><span style="color:red;">*</span>结束时间</label>
                    <div class="layui-input-block">
                        <input type="text" id="addEndTime" placeholder="结束时间" class="layui-input" />
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label"><span style="color:red;">*</span>生产人员</label>
                    <div class="layui-input-block">
                        <select id="addProducer" class="layui-select">
                            <option value="">请选择生产人员</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label"><span style="color:red;">*</span>单位</label>
                    <div class="layui-input-block">
                        <select id="addUnit" class="layui-select">
                            <option value="">请选择单位</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <!-- 新增：报工时长/效率等字段开始 -->
        <div class="form-section-title">绩效信息</div>
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">报工时长(小时)</label>
                    <div class="layui-input-block">
                        <input type="number" step="0.1" id="addReportHours" placeholder="小时" class="layui-input" />
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">报工时长(分钟)</label>
                    <div class="layui-input-block">
                        <input type="number" id="addReportMinutes" placeholder="分钟" class="layui-input" />
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">计价方式</label>
                    <div class="layui-input-block">
                        <select id="addPricingMethod" class="layui-select">
                            <option value="0">计件</option>
                            <option value="1">计时</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">标准效率</label>
                    <div class="layui-input-block">
                        <input type="text" id="addStandardEfficiency" placeholder="自动计算" class="layui-input" readonly style="background-color: #f5f5f5;" />
                        <div class="layui-form-mid layui-word-aux">件/小时（自动计算）</div>
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">实际效率</label>
                    <div class="layui-input-block">
                        <input type="text" id="addActualEfficiency" placeholder="自动计算" class="layui-input" readonly style="background-color: #f5f5f5;" />
                        <div class="layui-form-mid layui-word-aux">件/小时（自动计算）</div>
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">达标率(%)</label>
                    <div class="layui-input-block">
                        <input type="text" id="addComplianceRate" placeholder="自动计算" class="layui-input" readonly style="background-color: #f5f5f5;" />
                        <div class="layui-form-mid layui-word-aux">百分比（自动计算）</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space20">
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">工资单价</label>
                    <div class="layui-input-block">
                        <input type="number" step="0.01" id="addWageUnitPrice" placeholder="工资单价" class="layui-input" />
                    </div>
                </div>
            </div>
            <div class="layui-col-md4">
                <div class="layui-form-item">
                    <label class="layui-form-label">预计工资</label>
                    <div class="layui-input-block">
                        <input type="number" step="0.01" id="addEstimatedWage" placeholder="系统自动计算" class="layui-input" readonly style="background-color: #f8f8f8;" />
                    </div>
                </div>
            </div>
        </div>
        <!-- 新增：报工时长/效率等字段结束 -->
        <!-- （重复）生产人员/单位行已移除 -->

        <!-- 报工-不良品项子表 -->
        <fieldset class="layui-elem-field" style="margin-top:20px;">
            <legend>报工-不良品项</legend>
            <div style="margin-bottom:10px;">
                <button type="button" class="layui-btn layui-btn-sm" onclick="addDefectiveRow()"><i class="layui-icon layui-icon-addition"></i> 添加行</button>
                <button type="button" class="layui-btn layui-btn-danger layui-btn-sm" onclick="removeSelectedDefectiveRows()"><i class="layui-icon layui-icon-delete"></i> 删除选中</button>
                <button type="button" class="layui-btn layui-btn-warm layui-btn-sm" onclick="triggerImportDefective()"><i class="layui-icon layui-icon-download-circle"></i> 导入</button>
                <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" onclick="exportDefectiveItems()"><i class="layui-icon layui-icon-export"></i> 导出</button>
                <input type="file" id="defectiveImportFile" accept=".csv,.txt" style="display:none" />
            </div>
            <table class="layui-table" id="defectiveTable" lay-size="sm">
                <thead>
                    <tr>
                        <th style="text-align:center;"><input type="checkbox" id="defectiveSelectAll" lay-skin="primary"></th>
                        <th>不良品编号</th>
                        <th>数量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="defectiveTbody"></tbody>
            </table>
        </fieldset>
    </form>
</div>

@section Scripts {
    <script>
        let currentPage = 1;
        let pageSize = 10;
        let selectedIds = [];
        // 本页数据缓存，key=id
        let dataCache = {};
        // 排序状态 - 默认按工单排序
        let currentSortField = 'workOrderCode';
        let currentSortDirection = 'asc';
        
        // 前端字段名到后端字段名的映射
        const fieldMapping = {
            'workOrderCode': 'WorkOrderCode',
            'processName': 'ProcessName',
            'productNo': 'ProductNo',
            'productCode': 'ProductCode',
            'productName': 'ProductName',
            'productSpec': 'ProductSpec',
            'processStatus': 'ProcessStatus',
            'producer': 'Producer',
            'reportQty': 'ReportQty',
            'unit': 'Unit',
            'goodQty': 'GoodQty',
            'defectiveQty': 'DefectiveQty',
            'processProgress': 'ProcessProgress',
            'startTime': 'StartTime',
            'endTime': 'EndTime',
            'reportHours': 'ReportHours',
            'reportMinutes': 'ReportMinutes',
            'standardEfficiency': 'StandardEfficiency',
            'actualEfficiency': 'ActualEfficiency',
            'complianceRate': 'ComplianceRate',
            'pricingMethod': 'PricingMethod',
            'wageUnitPrice': 'WageUnitPrice',
            'estimatedWage': 'EstimatedWage',
            'approvalStatus': 'ApprovalStatus',
            'approver': 'Approver',
            'createTime': 'CreateTime',
            'creatorName': 'CreatorName',
            'modifierName': 'ModifierName',
            'modifyTime': 'ModifyTime'
        };
        // 单位下拉静态选项
        const UNIT_OPTIONS = ['个','箱','件','套','PCS','只','台','米','条','张','车','天','小时','分钟','周','月'];
        // Read API 基础地址
        const READ_API_URL = '@ViewBag.ReadApiUrl';
        // Write API 基础地址
        const WRITE_API_URL = '@ViewBag.WriteApiUrl';
        // 工具函数：将日期字符串转 ISO8601（后台要求）
        function toIso(val){
            if(!val) return null;
            if(val.includes('T')) return val;
            
            try {
                const d = new Date(val.replace(/-/g,'/'));
                if (isNaN(d.getTime())) {
                    console.warn('无效的日期格式:', val);
                    return val; // 返回原值，让后端处理
                }
                const isoString = d.toISOString();
                console.log('日期转换:', val, '->', isoString);
                return isoString;
            } catch (ex) {
                console.error('日期转换异常:', val, ex);
                return val;
            }
        }

        // 列设置（顺序 & 是否显示），可持久化在 localStorage
        // 默认列定义（顺序同截图需求）
        const DEFAULT_COLUMN_SETTINGS = [
            { field: 'workOrderCode',   title: '工单',             visible: true },
            { field: 'processName',     title: '工序名称',         visible: true },
            { field: 'productNo',       title: '产品',             visible: true },
            { field: 'productCode',     title: '产品编号',         visible: true },
            { field: 'productName',     title: '产品名称',         visible: true },
            { field: 'productSpec',     title: '产品规格',         visible: true },
            { field: 'processStatus',   title: '工序状态',         visible: true },
            { field: 'producer',        title: '生产人员',         visible: true },
            { field: 'reportQty',       title: '报工数',           visible: true },
            { field: 'unit',            title: '单位',             visible: true },
            { field: 'goodQty',         title: '良品数',           visible: true },
            { field: 'defectiveQty',    title: '不良品数',         visible: true },
            { field: 'processProgress', title: '工序进度',         visible: true },
            { field: 'startTime',       title: '开始时间',         visible: true },
            { field: 'endTime',         title: '结束时间',         visible: true },
            { field: 'reportHours',     title: '报工时长(小时)',   visible: true },
            { field: 'reportMinutes',   title: '报工时长(分钟)',   visible: true },
            { field: 'standardEfficiency',title:'标准效率',        visible: true },
            { field: 'actualEfficiency',title:'实际效率',          visible: true },
            { field: 'complianceRate',  title: '达标率',           visible: true },
            { field: 'pricingMethod',   title: '计价方式',         visible: true },
            { field: 'wageUnitPrice',   title: '工资单价',         visible: true },
            { field: 'estimatedWage',   title: '预计工资',         visible: true },
            { field: 'approvalStatus',  title: '审批状态',         visible: true },
            { field: 'approver',        title: '审批人',           visible: true },
            { field: 'createTime',      title: '创建时间',         visible: true },
            { field: 'creatorName',     title: '创建人',           visible: true },
            { field: 'modifierName',    title: '修改人',           visible: true },
            { field: 'modifyTime',      title: '修改时间',         visible: true }
        ];
        // 在默认列设置下方添加开关，关闭固定列能力
        const ENABLE_FIXED_COLUMNS = false; // 是否启用固定列（false = 关闭）

        let columnSettings = JSON.parse(localStorage.getItem('workReportColumnSettings') || 'null');
        // 当本地存储为空、格式错误或字段顺序与默认不一致时，回退到默认列定义
        if (!Array.isArray(columnSettings) ||
            columnSettings.length !== DEFAULT_COLUMN_SETTINGS.length ||
            columnSettings.map(c => c.field).join(',') !== DEFAULT_COLUMN_SETTINGS.map(c => c.field).join(',')) {
            columnSettings = DEFAULT_COLUMN_SETTINGS;
        }

        // 根据 columnSettings 动态渲染表头
        function applyColumnSettings() {
            const headerRow = $('#workReportHeaderRow');
            headerRow.find('th:not(:first)').remove();
            
            let fixedColumns = 0; // 固定列计数
            columnSettings.forEach(function (col, index) {
                if (!col.visible) return;
                
                // 根据当前排序字段设置正确的图标和样式
                let iconClass = 'layui-icon-up-down';
                let thClass = '';
                if (col.field === currentSortField) {
                    iconClass = currentSortDirection === 'asc' ? 'layui-icon-up' : 'layui-icon-down';
                    thClass = 'active-sort';
                }
                
                // 前3个重要列设为固定列（工单、工序名称、产品）
                let fixedClass = '';
                let leftPosition = '';
                if (ENABLE_FIXED_COLUMNS && fixedColumns < 3) {
                    fixedClass = 'fixed-column';
                    // 计算累积宽度：复选框列50px + 前面已固定列的宽度
                    let cumulativeWidth = 50; // 复选框列宽度
                    for (let i = 0; i < fixedColumns; i++) {
                        cumulativeWidth += 120; // 每个固定列120px宽度
                    }
                    leftPosition = `left: ${cumulativeWidth}px;`;
                    fixedColumns++;
                }
                
                // 添加拖拽调整功能
                const thHtml = `
                    <th onclick="sortTable('${col.field}')" 
                        class="${thClass} ${fixedClass}" 
                        style="cursor: pointer; user-select: none; min-width: 120px; ${leftPosition}" 
                        data-field="${col.field}">
                        ${col.title} 
                        <i class="layui-icon ${iconClass}"></i>
                        <div class="resize-handle" data-field="${col.field}"></div>
                    </th>
                `;
                
                headerRow.append(thHtml);
            });
            
            // 初始化拖拽功能
            initColumnResize();
            // 重新计算固定列位置，防止重叠
            updateFixedColumnPositions();
        }

        // 打开列设置弹窗
        function showColumnSettings() {
            layui.use(['layer', 'form'], function () {
                const layer = layui.layer;
                const form = layui.form;

                // 构建行
                const tbody = $('#columnSettingsTBody');
                tbody.empty();
                columnSettings.forEach(function (col, idx) {
                    tbody.append(`<tr data-field="${col.field}">
                        <td class="drag-handle layui-icon layui-icon-more-vertical"></td>
                        <td>${col.title}</td>
                        <td style="text-align:center;"><input type="checkbox" ${col.visible ? 'checked' : ''}></td>
                    </tr>`);
                });

                // 如果未加载 SortableJS，则动态加载
                function ensureSortable(callback) {
                    if (window.Sortable) { callback(); return; }
                    $.getScript('https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js', callback);
                }

                ensureSortable(function () {
                    new Sortable(tbody[0], {
                        handle: '.drag-handle',
                        animation: 150
                    });
                });

                layer.open({
                    type: 1,
                    title: '设置',
                    content: $('#columnSettingsModal'),
                    area: ['460px', '600px'],
                    shade: 0,
                    btn: ['确定', '重置', '取消'],
                    btn1: function (index) {
                        // 保存
                        const newSettings = [];
                        $('#columnSettingsTBody tr').each(function () {
                            const field = $(this).data('field');
                            const col = columnSettings.find(c => c.field === field);
                            col.visible = $(this).find('input[type="checkbox"]').is(':checked');
                            newSettings.push(col);
                        });
                        columnSettings = newSettings;
                        localStorage.setItem('workReportColumnSettings', JSON.stringify(columnSettings));
                        applyColumnSettings();
                        loadData();
                        layer.close(index);
                    },
                    btn2: function () {
                        // 重置到默认
                        localStorage.removeItem('workReportColumnSettings');
                        columnSettings = DEFAULT_COLUMN_SETTINGS;
                        applyColumnSettings();
                        loadData();
                        layer.msg('已重置为默认列');
                        return false; // 不关闭
                    },
                    success: function () { form.render(); }
                });
            });
        }

        // Layui 分页初始化
        $(function () {
            layui.use(['laypage', 'form'], function () {
                renderPagination(0);
                // 初始化工序名称下拉框
                initProcessOptions();
                // 初始化单位下拉框
                initUnitOptions();
                // 初始化生产人员下拉框
                initProducerOptions();
                // 初始化工单下拉框
                initWorkOrderOptions();
                // 初始化产品下拉框
                initProductOptions();
                // 设置产品联动
                setupProductLinkage();
            });
            applyColumnSettings();
            loadData();

            // 事件委托：动态生成的行复选框变化时，统一更新按钮状态
            $(document).on('change', '#workReportTableBody .row-checkbox', function(){
                updateSelected();
            });
            // 新增：表头全选框事件
            $(document).on('change', '#checkAll', function(){
                toggleSelectAll();
            });
        });

        // 初始化高级查询中的单位下拉框
        function initUnitOptions() {
            const unitSelect = $('#advUnit');
            unitSelect.empty();
            unitSelect.append('<option value="">请选择单位</option>');
            UNIT_OPTIONS.forEach(function(u){
                unitSelect.append(`<option value="${u}">${u}</option>`);
            });
            // 同步填充新增表单
            const addUnitSelect = $('#addUnit');
            if (addUnitSelect.length) {
                addUnitSelect.empty().append('<option value="">请选择单位</option>');
                UNIT_OPTIONS.forEach(function(u){
                    addUnitSelect.append(`<option value="${u}">${u}</option>`);
                });
            }
            // 重新渲染 select
            if (layui.form) layui.form.render('select');
        }

        // 初始化生产人员下拉框
        function initProducerOptions() {
            // 调用MVC后端来获取用户数据（MVC后端会处理JWT认证）
            $.ajax({
                url: '@Url.Action("GetUserPage", "Account")',
                type: 'GET',
                data: {
                    page: 1,
                    limit: 1000, // 获取所有用户
                    name: ''
                },
                success: function(resp) {
                    if (resp.code === 0 && resp.data) {
                        const producerSelect = $('#advProducer');
                        producerSelect.empty();
                        producerSelect.append('<option value="">生产人员</option>');
                        
                        resp.data.forEach(function(user) {
                            const realName = user.realName || user.name;
                            if (realName) {
                                producerSelect.append(`<option value="${realName}">${realName}</option>`);
                            }
                        });
                        // 同步填充新增表单
                        const addProducerSelect = $('#addProducer');
                        if (addProducerSelect.length) {
                            addProducerSelect.empty().append('<option value="">生产人员</option>');
                            resp.data.forEach(function(user) {
                                const realName = user.realName || user.name;
                                if (realName) {
                                    addProducerSelect.append(`<option value="${realName}">${realName}</option>`);
                                }
                            });
                        }
                        // 重新渲染 select
                        if (layui.form) layui.form.render('select');
                    } else {
                        console.warn('获取生产人员数据失败:', resp.msg || '未知错误');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('获取生产人员数据异常:', error);
                }
            });
        }

        // 初始化工序名称下拉框（基础查询 + 高级查询）
        function initProcessOptions() {
            const apiUrl = READ_API_URL + '/process/names';
            $.get(apiUrl)
                .done(function (resp) {
                    if (typeof resp === 'string') resp = JSON.parse(resp);
                    if (resp.code !== 200) {
                        layui.layer.msg(resp.msg || '加载工序名称失败', { icon: 2 });
                        return;
                    }
                    const list = resp.data || [];
                    const baseSelect = $('#processSelect');
                    const advSelect = $('#advProcessName');
                    const addSelect = $('#addProcessName');
                    baseSelect.empty().append('<option value="">请选择工序名称</option>');
                    advSelect.empty().append('<option value="">请选择工序名称</option>');
                    addSelect.empty().append('<option value="">请选择工序名称</option>');
                    list.forEach(function (item) {
                        const name = item.processName || item.ProcessName || '';
                        if (!name) return;
                        const optionHtml = `<option value="${name}">${name}</option>`;
                        baseSelect.append(optionHtml);
                        advSelect.append(optionHtml);
                        addSelect.append(optionHtml);
                    });
                    if (layui.form) layui.form.render('select');
                })
                .fail(function () {
                    layui.layer.msg('加载工序名称接口异常', { icon: 2 });
                });
        }

        function loadData() {
            // 将前端字段名映射到后端字段名
            const backendSortField = fieldMapping[currentSortField] || currentSortField;
            
            const params = {
                processName: $('#processSelect').val(),
                pageIndex: currentPage,
                pageSize: pageSize,
                sortField: backendSortField,
                sortDirection: currentSortDirection
            };
            $.ajax({
                url: '@Url.Action("SearchWorkReport", "WorkReport")',
                type: 'GET',
                data: params,
                success: function (resp) {
                    // 透传 JSON
                    if (typeof resp === 'string') resp = JSON.parse(resp);
                    if (resp.code !== 200) {
                        layui.layer.msg(resp.msg || '获取失败', { icon: 2 });
                        return;
                    }
                    renderTable(resp.data);
                    renderPagination(resp.data.total || 0);
                    // 确保排序图标状态正确
                    updateSortIcons();
                },
                error: function () {
                    layui.layer.msg('请求异常', { icon: 2 });
                }
            });
        }

        function renderTable(data) {
            const tbody = $('#workReportTableBody');
            tbody.empty();
            if (data.data && data.data.length) {
                dataCache = {};
                data.data.forEach(function (item) {
                    dataCache[item.id] = item;
                    let rowHtml = `<tr>`;
                    
                    // 复选框列（固定）
                    rowHtml += `<td style="text-align:center; width: 50px;">
                                   <input type="checkbox" class="row-checkbox" value="${item.id}" onchange="updateSelected(); toggleRowSelection(this)" ${selectedIds.includes(item.id) ? 'checked' : ''}>
                                </td>`;
                    
                    let fixedColumns = 0;
                    columnSettings.forEach(function (col) {
                        if (!col.visible) return;
                        
                        // 前3个重要列设为固定列
                        let fixedClass = '';
                        let leftPosition = '';
                        if (ENABLE_FIXED_COLUMNS && fixedColumns < 3) {
                            fixedClass = 'fixed-column';
                            // 计算累积宽度：复选框列50px + 前面已固定列的宽度
                            let cumulativeWidth = 50; // 复选框列宽度
                            for (let i = 0; i < fixedColumns; i++) {
                                cumulativeWidth += 120; // 每个固定列120px宽度
                            }
                            leftPosition = `left: ${cumulativeWidth}px;`;
                            fixedColumns++;
                        }
                        
                        const numericFields = ['reportQty','goodQty','defectiveQty','reportHours','reportMinutes','standardEfficiency','actualEfficiency','complianceRate','wageUnitPrice','estimatedWage'];
                        const dateFields = ['startTime','endTime','createTime','modifyTime'];
                        
                        let cellContent = '';
                        let cellStyle = `min-width: 120px; ${leftPosition}`;
                        
                        if (numericFields.includes(col.field)) {
                            cellStyle += ' text-align:right;';
                            const value = item[col.field] ?? '';
                            if (value !== '') {
                                const numValue = parseFloat(value);
                                let cssClass = 'numeric-data ';
                                if (numValue > 0) cssClass += 'positive';
                                else if (numValue === 0) cssClass += 'zero';
                                else cssClass += 'negative';
                                
                                if (['reportQty', 'goodQty', 'defectiveQty'].includes(col.field)) {
                                    cellContent = `<span class="quantity-display ${cssClass}">${value}</span>`;
                                } else {
                                    cellContent = `<span class="${cssClass}">${value}</span>`;
                                }
                            } else {
                                cellContent = '<span class="empty-data">-</span>';
                            }
                        } else if (dateFields.includes(col.field)) {
                            const dateValue = formatDate(item[col.field]);
                            cellContent = dateValue ? `<span class="time-display">${dateValue}</span>` : '<span class="empty-data">-</span>';
                        } else if (col.field === 'processName') {
                            const processName = item[col.field] ?? '';
                            cellContent = processName ? `<span class="process-name">${processName}</span>` : '<span class="empty-data">-</span>';
                        } else if (col.field === 'productCode') {
                            const productCode = item[col.field] ?? '';
                            cellContent = productCode ? `<span class="product-code">${productCode}</span>` : '<span class="empty-data">-</span>';
                        } else if (col.field === 'processStatus') {
                            const statusMap = { 
                                'NotStarted': { text: '未开始', class: 'status-pending' },
                                'InProgress': { text: '进行中', class: 'status-processing' },
                                'Completed': { text: '已完成', class: 'status-completed' }
                            };
                            const status = statusMap[item.processStatus] || { text: item.processStatus || '', class: 'status-pending' };
                            cellContent = `<span class="status-tag ${status.class}">${status.text}</span>`;
                        } else if (col.field === 'approvalStatus') {
                            const approvalMap = { 
                                'Pending': { text: '待审核', class: 'pending', tip: '工单已提交，等待审批' },
                                'Approved': { text: '已审核', class: 'approved', tip: '工单已通过审批' },
                                'Rejected': { text: '已驳回', class: 'rejected', tip: '工单被驳回，需要重新处理' }
                            };
                            const approval = approvalMap[item.approvalStatus] || { text: item.approvalStatus || '待审核', class: 'pending', tip: '待审核状态' };
                            cellContent = `<div class="approval-status ${approval.class}" title="${approval.tip}"><span class="approval-status-dot"></span>${approval.text}</div>`;
                        } else if (col.field === 'pricingMethod') {
                            const pricingMap = { 'ByPiece':'计件', 'ByHour':'计时' };
                            cellContent = pricingMap[item.pricingMethod] || item.pricingMethod || '';
                        } else {
                            const value = item[col.field] ?? '';
                            cellContent = value || '<span class="empty-data">-</span>';
                        }
                        
                        rowHtml += `<td class="${fixedClass}" style="${cellStyle}">${cellContent}</td>`;
                    });
                    
                    rowHtml += '</tr>';
                    tbody.append(rowHtml);
                });
            } else {
                const colspan = columnSettings.filter(c => c.visible).length + 1; // +1 复选框列
                tbody.append(`<tr><td colspan="${colspan}" style="text-align:center;color:#999;">暂无数据</td></tr>`);
            }
            updateSelected();
            // 渲染完数据后，更新固定列位置
            updateFixedColumnPositions();
        }

        function renderPagination(total) {
            layui.use('laypage', function () {
                const laypage = layui.laypage;
                laypage.render({
                    elem: 'workReportPager',
                    count: total,
                    curr: currentPage,
                    limit: pageSize,
                    limits: [10, 20, 30, 50, 100],
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                    jump: function (obj, first) {
                        if (!first) {
                            currentPage = obj.curr;
                            pageSize = obj.limit;
                            loadData();
                        }
                    }
                });
            });
        }

        function searchData() {
            currentPage = 1;
            loadData();
        }
        function resetSearch() {
            $('#processSelect').val('');
            currentPage = 1;
            loadData();
        }

        function formatDate(dateStr) {
            if (!dateStr) return '';
            const d = new Date(dateStr);
            return d.toLocaleString('zh-CN');
        }

        // 切换行选中状态
        function toggleRowSelection(checkbox) {
            const row = checkbox.closest('tr');
            if (checkbox.checked) {
                row.classList.add('selected');
            } else {
                row.classList.remove('selected');
            }
        }

        // 美化数字显示
        function formatNumber(value, decimals = 0) {
            if (value === null || value === undefined || value === '') return '-';
            const num = parseFloat(value);
            return isNaN(num) ? '-' : num.toLocaleString('zh-CN', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
        }

        // 新增：根据行复选框的选中数量同步表头全选框状态
        function updateCheckAll(){
            const total = $('#workReportTableBody .row-checkbox').length;
            const checked = $('#workReportTableBody .row-checkbox:checked').length;
            $('#checkAll').prop('checked', total > 0 && total === checked);
        }

        function updateSelected() {
            selectedIds = [];
            $('#workReportTableBody .row-checkbox:checked').each(function () {
                selectedIds.push(parseInt($(this).val()));
            });
            $('#deleteBtn').prop('disabled', selectedIds.length === 0);
            $('#editBtn').prop('disabled', selectedIds.length !== 1);
            // 新增：更新全选框
            updateCheckAll();
        }

        function toggleSelectAll() {
            const checked = $('#checkAll').prop('checked');
            if (checked) {
                // 跨页全选：调用后端获取所有 Id
                const query = {
                    processName: $('#processSelect').val()
                };
                layui.layer.load(1, { shade: 0 });
                $.get('@Url.Action("GetAllWorkReportIds", "WorkReport")', query, function (res) {
                    layui.layer.closeAll('loading');
                    if (res.code === 200) {
                        selectedIds = res.data || [];
                        $('#workReportTableBody .row-checkbox').prop('checked', true);
                        updateSelected();
                    } else {
                        layui.layer.msg(res.msg || '全选失败', { icon: 2 });
                        $('#checkAll').prop('checked', false);
                    }
                });
            } else {
                selectedIds = [];
                $('#workReportTableBody .row-checkbox').prop('checked', false);
                updateSelected();
            }
        }

        // 示例删除（仅提示）
        function deleteSelected() {
            if (selectedIds.length === 0) return;
            layui.layer.confirm(`确定删除选中的 ${selectedIds.length} 条数据吗？`, function (idx) {
                layui.layer.close(idx);
                // 调用批量删除接口
                layui.layer.load(1, { shade: 0.2 });
                $.ajax({
                    url: WRITE_API_URL + '/WorkReport/DeleteBatch',
                    type: 'DELETE',
                    contentType: 'application/json',
                    data: JSON.stringify({ Ids: selectedIds }),
                    success: function (resp) {
                        layui.layer.closeAll('loading');
                        if (typeof resp === 'string') resp = JSON.parse(resp);
                        if (resp.code === 200) {
                            layui.layer.msg('删除成功', { icon: 1 });
                            selectedIds = [];
                            currentPage = 1;
                            loadData();
                        } else {
                            layui.layer.msg(resp.msg || '删除失败', { icon: 2 });
                        }
                    },
                    error: function () {
                        layui.layer.closeAll('loading');
                        layui.layer.msg('删除接口异常', { icon: 2 });
                    }
                });
            });
        }

        function sortTable(field) {
            // 如果点击的是当前排序字段，则切换排序方向
            if (currentSortField === field) {
                currentSortDirection = currentSortDirection === 'asc' ? 'desc' : 'asc';
            } else {
                // 否则设置新的排序字段，默认降序
                currentSortField = field;
                currentSortDirection = 'desc';
            }
            
            // 重置到第一页
            currentPage = 1;
            
            // 更新表头排序图标
            updateSortIcons();
            
            // 重新加载数据
            loadData();
        }

        // 更新表头排序图标
        function updateSortIcons() {
            // 重置所有排序图标
            $('#workReportHeaderRow th i').removeClass('layui-icon-up layui-icon-down').addClass('layui-icon-up-down');
            
            // 找到当前排序字段对应的表头
            let thIndex = -1;
            let visibleColumnIndex = 0;
            columnSettings.forEach((col) => {
                if (col.visible) {
                    if (col.field === currentSortField) {
                        thIndex = visibleColumnIndex + 1; // +1 因为第一列是复选框
                    }
                    visibleColumnIndex++;
                }
            });
            
            if (thIndex > 0) {
                const sortIcon = $('#workReportHeaderRow th').eq(thIndex).find('i');
                sortIcon.removeClass('layui-icon-up-down');
                if (currentSortDirection === 'asc') {
                    sortIcon.addClass('layui-icon-up');
                } else {
                    sortIcon.addClass('layui-icon-down');
                }
            }
        }

        // 高级查询弹窗
        function showAdvancedSearch() {
            layui.use(['layer','form','laydate'], function () {
                var layer = layui.layer;
                var form = layui.form;
                var laydate = layui.laydate;

                // 初始化日期组件（只初始化一次）
                ['advStartTimeFrom','advStartTimeTo','advEndTimeFrom','advEndTimeTo'].forEach(function (id) {
                    if (!document.getElementById(id)._layDateRendered) {
                        laydate.render({ elem: '#' + id, type: 'datetime' });
                        document.getElementById(id)._layDateRendered = true;
                    }
                });

                layer.open({
                    type: 1,
                    title: '高级查询',
                    content: $('#advancedSearchModal'),
                    area: ['1080px', '680px'],
                    shade: 0,
                    btn: ['查询', '重置', '关闭'],
                    btn1: function (index) {
                        executeAdvancedSearch();
                        layer.close(index);
                    },
                    btn2: function () {
                        resetAdvancedSearch();
                        return false; // 不关闭
                    },
                    btn3: function (index) {
                        layer.close(index);
                    },
                    success: function(){ form.render(); }
                });
            });
        }

        function resetAdvancedSearch() {
            $('#advancedSearchForm')[0].reset();
            layui.form.render();
        }

        function executeAdvancedSearch() {
            // 将前端字段名映射到后端字段名
            const backendSortField = fieldMapping[currentSortField] || currentSortField;
            
            const params = {
                processName: $('#advProcessName').val(),
                productCode: $('#advProductCode').val(),
                productName: $('#advProductName').val(),
                processStatus: $('input[name="advProcessStatus"]:checked').val(),
                producer: $('#advProducer').val(),
                workOrder: $('#advWorkOrder').val(),
                unit: $('#advUnit').val(),
                reportQtyFrom: $('#advReportQtyFrom').val(),
                reportQtyTo: $('#advReportQtyTo').val(),
                goodQtyFrom: $('#advGoodQtyFrom').val(),
                goodQtyTo: $('#advGoodQtyTo').val(),
                startTimeFrom: $('#advStartTimeFrom').val(),
                startTimeTo: $('#advStartTimeTo').val(),
                endTimeFrom: $('#advEndTimeFrom').val(),
                endTimeTo: $('#advEndTimeTo').val(),
                pageIndex: 1,
                pageSize: pageSize,
                sortField: backendSortField,
                sortDirection: currentSortDirection
            };

            currentPage = 1;
            $.ajax({
                url: '@Url.Action("SearchWorkReport", "WorkReport")',
                type: 'GET',
                data: params,
                success: function (resp) {
                    if (typeof resp === 'string') resp = JSON.parse(resp);
                    if (resp.code === 200) {
                        renderTable(resp.data);
                        renderPagination(resp.data.total || 0);
                    } else {
                        layui.layer.msg(resp.msg || '查询失败', { icon: 2 });
                    }
                },
                error: function () {
                    layui.layer.msg('请求失败', { icon: 2 });
                }
            });
        }
        // 显示新增报工表单
        function showAddWorkReport() {
            // 清空子表
            $('#defectiveTbody').empty();
            $('#defectiveSelectAll').prop('checked',false);
            
            // 清除验证提示
            $('#quantityTip, #timeTip').remove();
            
            // 清空预计工资字段
            $('#addEstimatedWage').val('0.00');
            
            // 重新渲染表单元素
            if(typeof layui !== 'undefined' && layui.form){ 
                layui.form.render(); 
            }
            
            _openWorkReportModal('add');
        }

        // 显示编辑表单（仅单选）
        function editSelected(){
            if(selectedIds.length===0){layui.layer.msg('请选择要编辑的行',{icon:2});return;}
            if(selectedIds.length>1){layui.layer.msg('一次只能编辑一行',{icon:2});return;}
            const id = selectedIds[0];
            let row = dataCache[id];
            if(!row){
                const tr = $(`#workReportTableBody .row-checkbox[value='${id}']`).closest('tr');
                if(tr.length){
                    row = {id:id, workOrderCode: tr.find('td:eq(1)').text().trim()}; // 简要对象
                }
            }
            if(!row){layui.layer.msg('未找到行数据',{icon:2});return;}

            // 填充表单
            $('#workReportId').val(row.id);
            $('#addWorkOrderCode').val(row.workOrderCode);
            $('#addProcessName').val(row.processName);
            $('#addProductCode').val(row.productCode);
            $('#addProductName').val(row.productName);
            $('#addReportQty').val(row.reportQty);
            $('#addGoodQty').val(row.goodQty);
            $('#addDefectiveQty').val(row.defectiveQty);
            $('#addProducer').val(row.producer);
            $('#addUnit').val(row.unit);
            $('#addStartTime').val(formatDate(row.startTime));
            $('#addEndTime').val(formatDate(row.endTime));
            $('#addReportHours').val(row.reportHours);
            $('#addReportMinutes').val(row.reportMinutes);
            $('#addStandardEfficiency').val(row.standardEfficiency);
            $('#addActualEfficiency').val(row.actualEfficiency);
            $('#addComplianceRate').val(row.complianceRate);
            $('#addPricingMethod').val(row.pricingMethod);
            $('#addWageUnitPrice').val(row.wageUnitPrice);
            $('#addEstimatedWage').val(row.estimatedWage || '0.00');
            if(layui.form) layui.form.render('select');

            // 清空并重新填充不良品项子表
            $('#defectiveTbody').empty();
            $('#defectiveSelectAll').prop('checked', false);
            
            if(row.defectiveItems && row.defectiveItems.length > 0) {
                row.defectiveItems.forEach(item => {
                    addDefectiveRow(item);
                });
            }
            
            // 重新渲染表单元素
            if(typeof layui !== 'undefined' && layui.form){ 
                layui.form.render(); 
            }
            
            _openWorkReportModal('edit');
        }

        // 实时验证数量关系
        function setupRealTimeValidation() {
            // 监听报工数、良品数、不良品数的变化
            $('#addReportQty, #addGoodQty, #addDefectiveQty').on('input change', function() {
                validateQuantities();
            });
            
            // 监听时间变化
            $('#addStartTime, #addEndTime').on('change', function() {
                validateTimeRange();
            });
        }
        
        function validateQuantities() {
            const reportQty = parseInt($('#addReportQty').val() || 0);
            const goodQty = parseInt($('#addGoodQty').val() || 0);
            const defectiveQty = parseInt($('#addDefectiveQty').val() || 0);
            
            // 移除之前的提示
            $('#quantityTip').remove();
            
            if (reportQty > 0) {
                const sum = goodQty + defectiveQty;
                if (sum > reportQty) {
                    const tipHtml = `<div id="quantityTip" style="color:red;font-size:12px;margin-top:5px;">
                        ⚠️ 良品数(${goodQty}) + 不良品数(${defectiveQty}) = ${sum} > 报工数(${reportQty})
                    </div>`;
                    $('#addDefectiveQty').closest('.layui-form-item').append(tipHtml);
                } else if (sum < reportQty && sum > 0) {
                    const remaining = reportQty - sum;
                    const tipHtml = `<div id="quantityTip" style="color:orange;font-size:12px;margin-top:5px;">
                        💡 还有 ${remaining} 个产品未分配到良品或不良品
                    </div>`;
                    $('#addDefectiveQty').closest('.layui-form-item').append(tipHtml);
                }
            }
        }
        
        function validateTimeRange() {
            const startTime = $('#addStartTime').val();
            const endTime = $('#addEndTime').val();
            
            // 移除之前的提示
            $('#timeTip').remove();
            
            if (startTime && endTime) {
                const start = new Date(startTime);
                const end = new Date(endTime);
                
                if (start >= end) {
                    const tipHtml = `<div id="timeTip" style="color:red;font-size:12px;margin-top:5px;">
                        ⚠️ 结束时间必须晚于开始时间
                    </div>`;
                    $('#addEndTime').closest('.layui-form-item').append(tipHtml);
                } else {
                    // 计算时长
                    const duration = (end - start) / (1000 * 60 * 60); // 小时
                    const tipHtml = `<div id="timeTip" style="color:green;font-size:12px;margin-top:5px;">
                        ✓ 工作时长: ${duration.toFixed(1)} 小时
                    </div>`;
                    $('#addEndTime').closest('.layui-form-item').append(tipHtml);
                }
            }
        }

        // 在弹窗打开时初始化实时验证
        function _openWorkReportModal(mode){
            layui.use(['layer','form','laydate'], function(){
                var layer = layui.layer, form = layui.form, laydate = layui.laydate;

                ['addStartTime','addEndTime'].forEach(function(id){
                    if (!document.getElementById(id)._layDateRendered) {
                        laydate.render({ elem: '#' + id, type: 'datetime' });
                        document.getElementById(id)._layDateRendered = true;
                    }
                });

                layer.open({
                    type:1,
                    title: mode==='add'?'新增报工':'编辑报工',
                    content:$('#addWorkReportModal'),
                    area:['1000px','760px'],
                    shade:0,
                    btn:['提交','取消'],
                    btn1:function(index){
                        if(mode==='add') submitAddWorkReport(index); else submitEditWorkReport(index);
                    },
                    success:function(){ 
                        form.render(); 
                        // 初始化实时验证
                        setupRealTimeValidation();
                        // 清除之前的提示
                        $('#quantityTip, #timeTip').remove();
                        // 初始计算预计工资
                        setTimeout(function() {
                            calculateEstimatedWage();
                        }, 100);
                    }
                });
            });
        }

        // 表单验证函数
        function validateWorkReportForm() {
            const errors = [];
            
            // 必填字段验证
            const workOrderCode = $('#addWorkOrderCode').val().trim();
            if (!workOrderCode) {
                errors.push('工单号不能为空');
            }
            
            const processName = $('#addProcessName').val();
            if (!processName) {
                errors.push('工序名称不能为空');
            }
            
            const productCode = $('#addProductCode').val().trim();
            if (!productCode) {
                errors.push('产品编号不能为空');
            }
            
            const productName = $('#addProductName').val().trim();
            if (!productName) {
                errors.push('产品名称不能为空');
            }
            
            const reportQty = $('#addReportQty').val();
            if (!reportQty || isNaN(reportQty) || parseInt(reportQty) <= 0) {
                errors.push('报工数必须为大于0的数字');
            }
            
            const producer = $('#addProducer').val();
            if (!producer) {
                errors.push('生产人员不能为空');
            }
            
            const unit = $('#addUnit').val();
            if (!unit) {
                errors.push('单位不能为空');
            }
            
            const startTime = $('#addStartTime').val().trim();
            if (!startTime) {
                errors.push('开始时间不能为空');
            }
            
            const endTime = $('#addEndTime').val().trim();
            if (!endTime) {
                errors.push('结束时间不能为空');
            }
            
            // 时间逻辑验证
            if (startTime && endTime) {
                const start = new Date(startTime);
                const end = new Date(endTime);
                if (start >= end) {
                    errors.push('结束时间必须晚于开始时间');
                }
            }
            
            // 数量逻辑验证
            const goodQty = parseInt($('#addGoodQty').val() || 0);
            const defectiveQty = parseInt($('#addDefectiveQty').val() || 0);
            const totalReportQty = parseInt(reportQty || 0);
            
            if (goodQty < 0) {
                errors.push('良品数不能为负数');
            }
            
            if (defectiveQty < 0) {
                errors.push('不良品数不能为负数');
            }
            
            if (goodQty + defectiveQty > totalReportQty) {
                errors.push('良品数与不良品数之和不能超过报工数');
            }
            
            // 不良品项验证
            const defectiveItems = collectDefectiveItems();
            if (defectiveQty > 0 && defectiveItems.length === 0) {
                errors.push('不良品数大于0时，必须填写不良品项明细');
            }
            
            // 验证不良品项明细的完整性
            let defectiveItemsQtySum = 0;
            for (let i = 0; i < defectiveItems.length; i++) {
                const item = defectiveItems[i];
                if (!item.defectiveCode || !item.defectiveCode.trim()) {
                    errors.push(`第${i + 1}行不良品编号不能为空`);
                }
                if (item.defectiveQty <= 0) {
                    errors.push(`第${i + 1}行不良品数量必须大于0`);
                }
                defectiveItemsQtySum += item.defectiveQty;
            }
            
            if (defectiveItems.length > 0 && defectiveItemsQtySum !== defectiveQty) {
                errors.push(`不良品项明细数量总和(${defectiveItemsQtySum})与不良品数(${defectiveQty})不一致`);
            }
            
            return {
                isValid: errors.length === 0,
                errors: errors
            };
        }

        // 显示验证错误信息
        function showValidationErrors(errors) {
            let errorHtml = '<div style="text-align:left;"><p><strong>请修正以下错误：</strong></p><ul>';
            errors.forEach(error => {
                errorHtml += `<li>${error}</li>`;
            });
            errorHtml += '</ul></div>';
            
            layui.layer.alert(errorHtml, {
                icon: 2,
                title: '表单验证失败',
                area: ['500px', 'auto'],
                shadeClose: false
            });
        }

        // 提交编辑
        function submitEditWorkReport(layerIndex){
            // 表单验证
            const validation = validateWorkReportForm();
            if (!validation.isValid) {
                showValidationErrors(validation.errors);
                return;
            }

            const payload = {
                ...dataCache[$('#workReportId').val()] // 先复制原数据
            };

            // 工具函数
            const _txt = id=>$('#'+id).val().trim();
            const _num = id=>{
                const v = $('#'+id).val();
                return v===''? null : parseInt(v);
            };
            const _float = id=>{
                const v = $('#'+id).val();
                return v===''? null : parseFloat(v);
            };

            payload.workOrderCode = _txt('addWorkOrderCode') || payload.workOrderCode;
            payload.processName   = _txt('addProcessName')   || payload.processName;
            payload.productCode  = _txt('addProductCode')    || payload.productCode;
            payload.productName  = _txt('addProductName')    || payload.productName;

            const rq=_num('addReportQty');   if(rq!==null) payload.reportQty = rq;
            const gq=_num('addGoodQty');     if(gq!==null) payload.goodQty   = gq;
            const dq=_num('addDefectiveQty');if(dq!==null) payload.defectiveQty = dq;

            payload.producer   = _txt('addProducer') || payload.producer;
            payload.unit       = _txt('addUnit')     || payload.unit;

            const st=_txt('addStartTime'); if(st) payload.startTime=toIso(st);
            const et=_txt('addEndTime');   if(et) payload.endTime =toIso(et);

            const rh=_float('addReportHours'); if(rh!==null) payload.reportHours = rh;
            const rm=_num('addReportMinutes'); if(rm!==null) payload.reportMinutes = rm;
            // 效率相关字段由后端自动计算，不需要获取
            const wup=_float('addWageUnitPrice'); if(wup!==null) payload.wageUnitPrice = wup;

            const pmVal=$('#addPricingMethod').val();
            if(pmVal!==''){ payload.pricingMethod = parseInt(pmVal); }

            // 仍然覆盖子表
            payload.defectiveItems = collectDefectiveItems();
            payload.modifierId = 1;
            // 枚举字符串转数字
            const STATUS_MAP = { 'NotStarted':0,'未开始':0,'InProgress':1,'进行中':1,'Completed':2,'已完成':2 };
            const PRICE_MAP  = { 'ByPiece':0,'计件':0,'ByHour':1,'计时':1 };
            
            console.log('原始枚举值:', {
                processStatus: payload.processStatus,
                pricingMethod: payload.pricingMethod
            });
            
            payload.processStatus  = STATUS_MAP[payload.processStatus]  ?? payload.processStatus;
            payload.pricingMethod  = PRICE_MAP[payload.pricingMethod]  ?? payload.pricingMethod;
            
            console.log('转换后枚举值:', {
                processStatus: payload.processStatus,
                pricingMethod: payload.pricingMethod
            });
            
            console.log('提交的完整数据:', payload);

            layui.layer.load(1,{shade:0.2});
            $.ajax({
                url: WRITE_API_URL + '/WorkReport/Edit',
                type:'PUT',
                contentType:'application/json',
                data: JSON.stringify(payload),
                success:function(resp){
                    layui.layer.closeAll('loading');
                    if (typeof resp==='string') resp = JSON.parse(resp);
                    if (resp.code === 200){
                        layui.layer.msg('编辑成功',{icon:1});
                        selectedIds=[];
                        currentPage=1;
                        loadData();
                        layui.layer.close(layerIndex);
                    } else {
                        layui.layer.msg(resp.msg || '编辑失败',{icon:2});
                    }
                },
                error:function(xhr){
                    layui.layer.closeAll('loading');
                    console.error('编辑报工请求失败:', xhr);
                    console.error('状态码:', xhr.status);
                    console.error('响应文本:', xhr.responseText);
                    
                    let errorMsg = '接口异常';
                    try {
                        if (xhr.responseText) {
                            const errorResponse = JSON.parse(xhr.responseText);
                            if (errorResponse.msg) {
                                errorMsg = errorResponse.msg;
                            } else if (errorResponse.message) {
                                errorMsg = errorResponse.message;
                            }
                        }
                    } catch (e) {
                        console.error('解析错误响应失败:', e);
                    }
                    
                    if(xhr && xhr.responseText){
                        layui.layer.alert('后端返回：<br/>'+xhr.responseText,{icon:2,shade:0});
                    } else {
                        layui.layer.msg(errorMsg, {icon:2});
                    }
                }
            });
        }

        // 计算预计工资
        function calculateEstimatedWage() {
            const pricingMethod = parseInt($('#addPricingMethod').val() || 0);
            const wageUnitPrice = parseFloat($('#addWageUnitPrice').val() || 0);
            const goodQty = parseInt($('#addGoodQty').val() || 0);
            const reportHours = parseFloat($('#addReportHours').val() || 0);
            const reportMinutes = parseInt($('#addReportMinutes').val() || 0);
            
            let estimatedWage = 0;
            
            if (pricingMethod === 0) {
                // 计件方式：预计工资 = 合格数量 × 工资单价
                estimatedWage = goodQty * wageUnitPrice;
            } else if (pricingMethod === 1) {
                // 计时方式：预计工资 = 总时长(小时) × 工资单价
                const totalHours = reportHours + (reportMinutes / 60);
                estimatedWage = totalHours * wageUnitPrice;
            }
            
            // 更新预计工资字段
            $('#addEstimatedWage').val(estimatedWage.toFixed(2));
            
            console.log('💰 预计工资计算:', {
                pricingMethod: pricingMethod === 0 ? '计件' : '计时',
                wageUnitPrice: wageUnitPrice,
                goodQty: goodQty,
                reportHours: reportHours,
                reportMinutes: reportMinutes,
                estimatedWage: estimatedWage.toFixed(2)
            });
            
            return estimatedWage;
        }

        // 提交新增数据
        function submitAddWorkReport(layerIndex) {
            // 表单验证
            const validation = validateWorkReportForm();
            if (!validation.isValid) {
                showValidationErrors(validation.errors);
                return;
            }

            // 调试：获取产品规格信息
            const selectedProductOption = $('#addProductCode').find('option:selected');
            const productSpec = selectedProductOption.data('product-spec') || '';
            
            console.log('🔍 提交数据调试信息:');
            console.log('选中的产品编号:', $('#addProductCode').val());
            console.log('选中的选项:', selectedProductOption);
            console.log('选项的所有data属性:', selectedProductOption.data());
            console.log('产品规格值:', productSpec);
            console.log('产品名称:', $('#addProductName').val());
            
            const payload = {
                workOrderCode: $('#addWorkOrderCode').val(),
                processName: $('#addProcessName').val(),
                productCode: $('#addProductCode').val(),
                productName: $('#addProductName').val(),
                productNo: $('#addProductCode').val(),
                productSpec: productSpec,
                reportQty: parseInt($('#addReportQty').val()||0),
                producer: $('#addProducer').val(),
                unit: $('#addUnit').val(),
                goodQty: parseInt($('#addGoodQty').val()||0),
                defectiveQty: parseInt($('#addDefectiveQty').val()||0),
                processStatus: 2,
                processProgress: '100%',
                startTime: toIso($('#addStartTime').val()),
                endTime: toIso($('#addEndTime').val()),
                reportHours: parseFloat($('#addReportHours').val() || 0),
                reportMinutes: parseInt($('#addReportMinutes').val() || 0),
                // 效率字段由后端自动计算，不需要从表单获取
                pricingMethod: parseInt($('#addPricingMethod').val() || 0),
                wageUnitPrice: parseFloat($('#addWageUnitPrice').val() || 0),
                estimatedWage: calculateEstimatedWage(),
                bonusAmount:0,
                penaltyAmount:0,
                creatorId: 1,
                defectiveItems: collectDefectiveItems()
            };

            console.log('📤 最终提交的报工数据:', JSON.stringify(payload, null, 2));
            
            // 特别检查产品相关字段
            if (!payload.productSpec || payload.productSpec.trim() === '') {
                console.warn('⚠️ 警告: 产品规格字段为空!');
                console.log('请检查产品数据是否正确加载，以及是否在数据库中有规格信息');
            } else {
                console.log('✅ 产品规格字段正常:', payload.productSpec);
            }

            layui.layer.load(1,{shade:0.2});
            $.ajax({
                url: WRITE_API_URL + '/WorkReport/Add',
                type:'POST',
                contentType:'application/json',
                data: JSON.stringify(payload),
                success:function(resp){
                    layui.layer.closeAll('loading');
                    if (typeof resp==='string') resp = JSON.parse(resp);
                    if (resp.code === 200){
                        layui.layer.msg('新增成功',{icon:1});
                        currentPage=1;
                        loadData();
                        layui.layer.close(layerIndex);
                    } else {
                        layui.layer.msg(resp.msg || '新增失败',{icon:2});
                    }
                },
                error:function(xhr){
                    layui.layer.closeAll('loading');
                    if(xhr && xhr.responseText){
                        layui.layer.alert('后端返回：<br/>'+xhr.responseText,{icon:2,shade:0});
                    }
                    layui.layer.msg('接口异常',{icon:2});
                }
            });
        }

        // 组装不良品数组
        function collectDefectiveItems(){
            const list = [];
            $('#defectiveTbody tr').each(function(){
                const code = $(this).find('.defective-code').val().trim();
                const qty  = parseInt($(this).find('.defective-qty').val()||0);
                if(code){list.push({defectiveCode:code,defectiveQty:qty});}
            });
            return list;
        }

        // 导入功能：选择文件
        function triggerImportDefective(){
            document.getElementById('defectiveImportFile').click();
        }

        // 监听文件变化
        $('#defectiveImportFile').off('change').on('change', function(){
            const file = this.files[0];
            if(!file) return;
            const reader = new FileReader();
            reader.onload = function(e){
                const text = e.target.result;
                parseDefectiveCSV(text);
            };
            reader.readAsText(file,'utf-8');
            // 清空选择
            $(this).val('');
        });

        // 解析 CSV 内容（两列：代码,数量）
        function parseDefectiveCSV(text){
            if(!text) { layui.layer.msg('文件内容为空',{icon:2}); return; }
            const lines = text.split(/\r?\n/);
            let imported = 0;
            lines.forEach(line=>{
                const parts = line.split(',');
                if(parts.length>=2){
                    const code = parts[0].trim();
                    const qty = parseInt(parts[1]);
                    if(code){
                        addDefectiveRow({defectiveCode:code,defectiveQty:isNaN(qty)?0:qty});
                        imported++;
                    }
                }
            });
            layui.layer.msg(`已导入 ${imported} 条不良品项`,{icon:1});
        }

        function addDefectiveRow(item={defectiveCode:'',defectiveQty:0}){
             const rowId = Date.now()+''+Math.floor(Math.random()*1000);
             const html = `<tr data-id="${rowId}">
                 <td style="text-align:center;"><input type="checkbox" class="defective-row-check" lay-skin="primary"></td>
                 <td><input type="text" class="layui-input defective-code" value="${item.defectiveCode||''}" placeholder="不良品编号"/></td>
                 <td><input type="number" class="layui-input defective-qty" value="${item.defectiveQty||0}" min="0"/></td>
                 <td style="text-align:center;"><button type="button" class="layui-btn layui-btn-xs layui-btn-danger" onclick="removeDefectiveRow(this)"><i class="layui-icon layui-icon-close"></i></button></td>
             </tr>`;
             $('#defectiveTbody').append(html);
             
             // 若已全选，则勾选新行
             if($('#defectiveSelectAll').prop('checked')){
                 $('#defectiveTbody tr:last .defective-row-check').prop('checked', true);
             }
             
             // 更新全选状态
             updateDefectiveSelectAll();
             
             // 重新渲染 Layui 复选框
             if(typeof layui !== 'undefined' && layui.form){ 
                 layui.form.render('checkbox'); 
             }
             
             console.log('添加不良品项行，当前行数:', $('#defectiveTbody tr').length);
         }

         // 移除单个不良品项行
         function removeDefectiveRow(btn) {
             $(btn).closest('tr').remove();
             updateDefectiveSelectAll();
             console.log('删除不良品项行，剩余行数:', $('#defectiveTbody tr').length);
         }

         function removeSelectedDefectiveRows(){
             const selectedCount = $('#defectiveTbody .defective-row-check:checked').length;
             console.log('准备删除', selectedCount, '个选中的不良品项行');
             
             $('#defectiveTbody .defective-row-check:checked').each(function(){
                 $(this).closest('tr').remove();
             });
             
             // 重置全选状态
             $('#defectiveSelectAll').prop('checked', false);
             updateDefectiveSelectAll();
             
             if(typeof layui !== 'undefined' && layui.form){ 
                 layui.form.render('checkbox'); 
             }
             
             console.log('删除完成，剩余行数:', $('#defectiveTbody tr').length);
         }

         function toggleDefectiveSelectAll(){
            const checked = $('#defectiveSelectAll').prop('checked');
            console.log('不良品项全选状态:', checked);
            
            // 设置所有行的选中状态
            $('#defectiveTbody .defective-row-check').each(function(){
                $(this).prop('checked', checked);
            });
            
            // 重新渲染 Layui 复选框样式
            if(typeof layui !== 'undefined' && layui.form){ 
                layui.form.render('checkbox'); 
            }
            
            console.log('已更新', $('#defectiveTbody .defective-row-check').length, '个复选框状态为:', checked);
        }

        // 更新全选框状态（行删除或单行取消时调用）
        function updateDefectiveSelectAll(){
            const total = $('#defectiveTbody .defective-row-check').length;
            const checked = $('#defectiveTbody .defective-row-check:checked').length;
            const shouldCheck = total > 0 && total === checked;
            
            console.log('不良品项状态更新:', {total, checked, shouldCheck});
            
            $('#defectiveSelectAll').prop('checked', shouldCheck);
            
            // 重新渲染 Layui 复选框样式
            if(typeof layui !== 'undefined' && layui.form){ 
                layui.form.render('checkbox'); 
            }
        }

        // 事件委托：行复选框点击后同步 header
        $(document).on('change','#defectiveTbody .defective-row-check',function(){
            console.log('不良品项行复选框状态改变');
            updateDefectiveSelectAll();
        });

        // 事件委托：全选按钮点击处理
        $(document).on('click','#defectiveSelectAll',function(){
            // 使用延迟执行，确保checkbox状态已更新
            setTimeout(function(){
                toggleDefectiveSelectAll();
            }, 10);
        });

        // 导出报工数据
        function exportWorkReport(){
            // 获取当前搜索条件
            const searchParams = new URLSearchParams();
            
            // 基础搜索条件
            const processName = $('#processSelect').val();
            if(processName) searchParams.append('processName', processName);
            
            // 高级搜索条件
            const advProcessName = $('#advProcessName').val();
            if(advProcessName) searchParams.append('processName', advProcessName);
            
            const advProductCode = $('#advProductCode').val();
            if(advProductCode) searchParams.append('productCode', advProductCode);
            
            const advProductName = $('#advProductName').val();
            if(advProductName) searchParams.append('productName', advProductName);
            
            const advProcessStatus = $('input[name="advProcessStatus"]:checked').val();
            if(advProcessStatus !== undefined && advProcessStatus !== '') searchParams.append('processStatus', advProcessStatus);
            
            const advProducer = $('#advProducer').val();
            if(advProducer) searchParams.append('producer', advProducer);
            
            const advWorkOrder = $('#advWorkOrder').val();
            if(advWorkOrder) searchParams.append('workOrderCode', advWorkOrder);
            
            const advStartTimeFrom = $('#advStartTimeFrom').val();
            if(advStartTimeFrom) searchParams.append('startDate', toIso(advStartTimeFrom));
            
            const advEndTimeFrom = $('#advEndTimeFrom').val();
            if(advEndTimeFrom) searchParams.append('endDate', toIso(advEndTimeFrom));
            
            // 设置导出格式为xlsx
            searchParams.append('exportFormat', 'xlsx');
            
            // 构建导出URL
            const exportUrl = WRITE_API_URL + '/WorkReport/Export?' + searchParams.toString();
            
            console.log('导出URL:', exportUrl);
            
            // 显示加载提示
            const loadingIndex = layui.layer.load(1, {
                shade: [0.1, '#fff']
            });
            
            // 使用fetch下载文件
            fetch(exportUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.blob();
                })
                .then(blob => {
                    // 创建下载链接
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    a.download = `报工数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                    
                    layui.layer.close(loadingIndex);
                    layui.layer.msg('导出成功！', {icon: 1});
                })
                .catch(error => {
                    layui.layer.close(loadingIndex);
                    console.error('导出失败:', error);
                    layui.layer.msg('导出失败：' + error.message, {icon: 2});
                });
        }

        // 导出不良品项子表
        function exportDefectiveItems(){
            const id = $('#workReportId').val();
            if(!id){ layui.layer.msg('请先保存报工记录',{icon:2}); return; }
            const url = WRITE_API_URL + '/WorkReportDefectiveItem/Export?WorkReportId=' + id;
            window.open(url, '_blank');
        }

        // 页面初始化
        $(document).ready(function() {
            // 应用列设置（现在会自动设置正确的排序图标）
            applyColumnSettings();
            // 初始化工序选项
            initProcessOptions();
            // 初始化生产人员选项
            initProducerOptions();
            // 初始化工单下拉框
            initWorkOrderOptions();
            // 初始化产品选项
            initProductOptions();
            // 设置产品联动
            setupProductLinkage();
            // 加载数据
            loadData();
        });

        // 初始化工单下拉框（高级查询）
        function initWorkOrderOptions() {
            const apiUrl = READ_API_URL + '/WorkOrder/page';
            $.ajax({
                url: apiUrl,
                type: 'GET',
                success: function (resp) {
                    if (typeof resp === 'string') resp = JSON.parse(resp);
                    if (resp.code !== 200) {
                        layui.layer.msg(resp.msg || '加载工单列表失败', { icon: 2 });
                        return;
                    }
                    const list = resp.pageData || [];
                    const selects = $('#advWorkOrder, #addWorkOrderCode');
                    selects.empty().append('<option value="">请选择工单</option>');
                    list.forEach(function (item) {
                        const code = item.code || item.Code || '';
                        if (!code) return;
                        const name = item.productName || '';
                        const spec = item.spec || '';
                        const unit = item.unit || '';
                        let displayText = code;
                        if (name) {
                            displayText += ' - ' + name;
                            if (spec || unit) {
                                displayText += ' (' + [spec, unit].filter(Boolean).join(' ') + ')';
                            }
                        }
                        selects.append(`<option value="${code}">${displayText}</option>`);
                    });
                    if (layui.form) layui.form.render('select');
                },
                error: function (xhr, status, error) {
                    console.error('获取工单数据异常:', error);
                    layui.layer.msg('加载工单接口异常', { icon: 2 });
                }
            });
        }

        // 初始化产品下拉框
        function initProductOptions() {
            const apiUrl = READ_API_URL + '/Product/GetAllProducts';
            $.ajax({
                url: apiUrl,
                type: 'GET',
                success: function (resp) {
                    if (typeof resp === 'string') resp = JSON.parse(resp);
                    if (resp.code !== 200) {
                        layui.layer.msg(resp.msg || '加载产品列表失败', { icon: 2 });
                        return;
                    }
                    const list = resp.data || [];
                    const productCodeSelect = $('#addProductCode');
                    const productNameSelect = $('#addProductName');
                    
                    console.log('📦 产品数据加载成功:', list); // 调试日志
                    
                    // 清空并初始化选项
                    productCodeSelect.empty().append('<option value="">请选择产品编号</option>');
                    productNameSelect.empty().append('<option value="">请选择产品名称</option>');
                    
                    list.forEach(function (item) {
                        const code = item.code || '';
                        const name = item.name || '';
                        const spec = item.spec || '';
                        const unit = item.unit || '';
                        
                        console.log(`产品信息 - 编号:${code}, 名称:${name}, 规格:${spec}, 单位:${unit}`); // 调试日志
                        
                        if (code) {
                            // 产品编号下拉框：显示 "编号 - 名称 (规格 单位)"
                            let codeDisplayText = code;
                            if (name) {
                                codeDisplayText += ' - ' + name;
                                if (spec || unit) {
                                    codeDisplayText += ' (' + [spec, unit].filter(Boolean).join(' ') + ')';
                                }
                            }
                            productCodeSelect.append(`<option value="${code}" data-product-id="${item.id}" data-product-name="${name}" data-product-spec="${spec}" data-product-unit="${unit}">${codeDisplayText}</option>`);
                        }
                        
                        if (name) {
                            // 产品名称下拉框：显示 "名称 - 编号 (规格 单位)"
                            let nameDisplayText = name;
                            if (code) {
                                nameDisplayText += ' - ' + code;
                                if (spec || unit) {
                                    nameDisplayText += ' (' + [spec, unit].filter(Boolean).join(' ') + ')';
                                }
                            }
                            productNameSelect.append(`<option value="${name}" data-product-id="${item.id}" data-product-code="${code}" data-product-spec="${spec}" data-product-unit="${unit}">${nameDisplayText}</option>`);
                        }
                    });
                    
                    // 重新渲染 select
                    if (layui.form) layui.form.render('select');
                    console.log('✅ 产品选项初始化完成'); // 调试日志
                },
                error: function (xhr, status, error) {
                    console.error('获取产品数据异常:', error);
                    layui.layer.msg('加载产品接口异常', { icon: 2 });
                }
            });
        }

        // 设置产品编号和产品名称的联动
        function setupProductLinkage() {
            // 监听产品编号选择变化
            $(document).on('change', '#addProductCode', function() {
                const selectedOption = $(this).find('option:selected');
                const productName = selectedOption.data('product-name') || '';
                const productSpec = selectedOption.data('product-spec') || '';
                const productUnit = selectedOption.data('product-unit') || '';
                
                console.log('🔄 产品编号选择变化:', {
                    productCode: $(this).val(),
                    productName: productName,
                    productSpec: productSpec,
                    productUnit: productUnit,
                    allData: selectedOption.data()
                });
                
                if (productName) {
                    // 自动选择对应的产品名称
                    $('#addProductName').val(productName);
                    if (layui.form) layui.form.render('select');
                }
                
                // 如果存在产品规格字段，同步更新（备用方案）
                if ($('#addProductSpec').length > 0) {
                    $('#addProductSpec').val(productSpec);
                }
                
                // 如果存在单位字段，同步更新
                if ($('#addUnit').length > 0 && productUnit) {
                    $('#addUnit').val(productUnit);
                    if (layui.form) layui.form.render('select');
                }
            });
            
            // 监听产品名称选择变化
            $(document).on('change', '#addProductName', function() {
                const selectedOption = $(this).find('option:selected');
                const productCode = selectedOption.data('product-code') || '';
                const productSpec = selectedOption.data('product-spec') || '';
                const productUnit = selectedOption.data('product-unit') || '';
                
                console.log('🔄 产品名称选择变化:', {
                    productName: $(this).val(),
                    productCode: productCode,
                    productSpec: productSpec,
                    productUnit: productUnit,
                    allData: selectedOption.data()
                });
                
                if (productCode) {
                    // 自动选择对应的产品编号
                    $('#addProductCode').val(productCode);
                    if (layui.form) layui.form.render('select');
                }
                
                // 如果存在产品规格字段，同步更新（备用方案）
                if ($('#addProductSpec').length > 0) {
                    $('#addProductSpec').val(productSpec);
                }
                
                // 如果存在单位字段，同步更新
                if ($('#addUnit').length > 0 && productUnit) {
                    $('#addUnit').val(productUnit);
                    if (layui.form) layui.form.render('select');
                }
            });
        }

        // 实时计算并显示效率预览
        function calculateEfficiencyPreview() {
            const reportQty = parseInt($('#addReportQty').val() || 0);
            const reportHours = parseFloat($('#addReportHours').val() || 0);
            const reportMinutes = parseInt($('#addReportMinutes').val() || 0);
            
            // 计算总工时（小时）
            const totalHours = reportHours + reportMinutes / 60;
            
            let standardEfficiency = 10; // 标准值（每小时10件）
            let actualEfficiency = 0;
            let complianceRate = 0;
            
            if (totalHours > 0 && reportQty > 0) {
                // 实际效率 = 产量 / 工时（件/小时）
                actualEfficiency = Math.round((reportQty / totalHours) * 100) / 100;
                
                // 达标率 = (实际效率 / 标准效率) × 100%
                if (standardEfficiency > 0) {
                    complianceRate = Math.round((actualEfficiency / standardEfficiency) * 10000) / 100;
                }
            }
            
            // 更新显示
            $('#addStandardEfficiency').val(standardEfficiency.toFixed(2));
            $('#addActualEfficiency').val(actualEfficiency.toFixed(2));
            $('#addComplianceRate').val(complianceRate.toFixed(2));
        }

        // 初始化列宽拖拽调整功能
        function initColumnResize() {
            let isResizing = false;
            let currentColumn = null;
            let startX = 0;
            let startWidth = 0;
            
            // 为拖拽句柄绑定事件
            $(document).off('mousedown.resize').on('mousedown.resize', '.resize-handle', function(e) {
                e.stopPropagation();
                isResizing = true;
                currentColumn = $(this).parent();
                startX = e.pageX;
                startWidth = currentColumn.outerWidth();
                
                currentColumn.addClass('resizing');
                $('body').addClass('col-resizing').css('cursor', 'col-resize');
            });
            
            // 鼠标移动时调整列宽
            $(document).off('mousemove.resize').on('mousemove.resize', function(e) {
                if (!isResizing) return;
                
                const deltaX = e.pageX - startX;
                const newWidth = Math.max(80, startWidth + deltaX); // 最小宽度80px
                
                currentColumn.css('width', newWidth + 'px');
                
                // 同时调整对应的数据列
                const field = currentColumn.data('field');
                const columnIndex = currentColumn.index();
                $(`#workReportTableBody tr`).each(function() {
                    $(this).find(`td:eq(${columnIndex})`).css('width', newWidth + 'px');
                });
            });
            
            // 鼠标抬起时结束调整
            $(document).off('mouseup.resize').on('mouseup.resize', function() {
                if (isResizing) {
                    isResizing = false;
                    if (currentColumn) {
                        currentColumn.removeClass('resizing');
                        currentColumn = null;
                    }
                    $('body').removeClass('col-resizing').css('cursor', '');
                    // 列宽调整完毕后刷新固定列位置
                    updateFixedColumnPositions();
                }
            });
            
            // 双击句柄自动调整列宽
            $(document).off('dblclick.resize').on('dblclick.resize', '.resize-handle', function(e) {
                e.stopPropagation();
                const column = $(this).parent();
                const field = column.data('field');
                
                // 自动调整为内容适应宽度（这里可以根据需要实现具体逻辑）
                column.css('width', 'auto');
            });
        }
        


        // 页面加载完成后绑定事件
        $(document).ready(function() {
            // 绑定输入事件，实时计算预览
            $(document).on('input change', '#addReportQty, #addReportHours, #addReportMinutes', function() {
                calculateEfficiencyPreview();
            });
            
            // 初始计算一次
            calculateEfficiencyPreview();
            
            // 添加预计工资计算的事件监听器
            $(document).on('change input', '#addPricingMethod, #addWageUnitPrice, #addGoodQty, #addReportHours, #addReportMinutes', function() {
                calculateEstimatedWage();
            });
            
            // 初始化拖拽功能
            initColumnResize();
        });

        // 计算并更新固定列 left 值，防止列宽变化导致重叠
        function updateFixedColumnPositions() {
            if (!ENABLE_FIXED_COLUMNS) return; // 固定列已关闭，直接返回
            const headerFixed = $('#workReportHeaderRow th.fixed-column');
            if (headerFixed.length === 0) return;

            // 累积宽度，从 0 开始，逐列相加
            let cumulative = 0;
            headerFixed.each(function (idx) {
                // 设置当前表头列的 left
                $(this).css('left', cumulative + 'px');

                // 同步 tbody 每行中对应的固定列
                $('#workReportTableBody tr').each(function () {
                    $(this).find('td.fixed-column').eq(idx).css('left', cumulative + 'px');
                });

                // 将当前列宽加入累积值，为下一列计算 left
                cumulative += $(this).outerWidth();
            });
        }
    </script>
} 